package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.common.contants.wemedia.WemediaContans;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import com.usian.wemedia.mapper.WmmaterialMapper;
import com.usian.wemedia.mapper.WmnewsMapper;
import com.usian.wemedia.mapper.WmnewsMaterialMapper;
import com.usian.wemedia.service.WmnewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmnewsServiceImpl extends BaseServiceImpl<WmnewsMapper, WmNews> implements WmnewsService {
    @Autowired
    WmmaterialMapper wmmaterialMapper;
    @Autowired
    WmnewsMaterialMapper wmnewsMaterialMapper;
    @Autowired
    KafkaTemplate kafkaTemplate;
    @Value("${fdfs.url}")
    private String baseUrl;
    @Override
    public ResponseResult findWmnewsList(WmNewsPageReqDto dto) {
        if (dto == null) return errorParam;
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNews::getUserId, ThreadLocalUtils.getUser());
        if (dto.getStatus() !=null) wrapper.eq(WmNews::getStatus,dto.getStatus());
        if (dto.getChannelId() !=null) wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        if (dto.getKeyword() !=null) wrapper.eq(WmNews::getTitle,dto.getKeyword());
        if (dto.getMinTime()==null) dto.setMinTime(new Date());
        wrapper.lt(WmNews::getPublishTime,dto.getMinTime());
        wrapper.orderByDesc(WmNews::getPublishTime);
        return getPage(dto,wrapper);
    }

    @Override
    public ResponseResult submitNews(WmNewsDto wmNews) {
        if (wmNews == null) return errorParam;
        WmNews news = new WmNews();
        BeanUtils.copyProperties(wmNews,news);
        Integer newsId = news.getId();
        Boolean flag = false;
        if (newsId==null){
            Date date = new Date();
            news.setCreatedTime(date);
            news.setSubmitedTime(date);
            news.setUserId(ThreadLocalUtils.getUser());
            if (news.getType()==(short)-1) news.setType(null);
            flag = save(news);
        }else {
            //删除中间表数据
            wmnewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,newsId));
        }
        createsbz(news,wmNews);
        if (flag)kafkaTemplate.send(WemediaContans.AUTO_SCAN,news.getId()+"");
        return successParam;
    }

    @Override
    public WmNews findById(Integer id) {
        if (id==null) return null;
        WmNews news = getById(id);
        if (news==null)return null;
        return news;
    }

    @Override
    public ResponseResult delById(Integer id) {
        if (id==null) return errorParam;
        WmNews news = getById(id);
        if (news==null) return notExit;
        wmnewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,id));
        removeById(id);
        return successParam;
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto==null) return errorParam;
        if (dto.getId()==null||dto.getEnable()==null&&(dto.getEnable()!=0||dto.getEnable()!=1))return errorParam;
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null)return errorParam;
        if (wmNews.getStatus()!=9)return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"未发布的文章无法上下架");
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        HashMap<String, String> map = new HashMap<>();
        map.put("articleId",wmNews.getArticleId().toString());
        map.put("enable",dto.getEnable().toString());
        kafkaTemplate.send(WemediaContans.DOWNORUP, JSON.toJSONString(map));
        return successParam;
    }

    @Override
    public ResponseResult update(WmNews wmNews) {
        if (wmNews == null) return errorParam;
        updateById(wmNews);
        return successParam;
    }

    @Override
    public List<Integer> getIds() {
        List<WmNews> wmNews = baseMapper.selectList(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8));
        return wmNews.stream().map(w -> w.getId()).collect(Collectors.toList());
    }

    private void createsbz(WmNews news,WmNewsDto wmNews){
        ArrayList<String> imgUrlList = new ArrayList<>();
        String content = news.getContent();
        List<Map> list = JSON.parseArray(content, Map.class);
        for (Map map : list) {
            if (map.get("type").equals("image")){
                imgUrlList.add(map.get("value").toString().replace(baseUrl,""));
            }
        }
        //创建中间表内容关联表数据
        createNewsMaterial(news,imgUrlList, WemediaContans.WM_CONTENT_REFERENCE);
        if (news.getType()!=null){//不是自动获取主图
            List<String> images = wmNews.getImages();
            news.setImages(images.size()>=3?(images.get(0)+","+images.get(1)+","+images.get(2)).replaceAll(baseUrl,""):images.get(0).replace(baseUrl,""));
            createNewsMaterial(news,images,WemediaContans.WM_COVER_REFERENCE);
        }else {
            if (imgUrlList.size()>0){
                List<String> newList = imgUrlList.size()>=3?Arrays.asList(imgUrlList.get(0),imgUrlList.get(1),imgUrlList.get(2)):Arrays.asList(imgUrlList.get(0));
                news.setImages(imgUrlList.size()>=3?(imgUrlList.get(0)+","+imgUrlList.get(1)+","+imgUrlList.get(2)).replaceAll(baseUrl,""):imgUrlList.get(0).replace(baseUrl,""));
                news.setType(newList.size()<3?WemediaContans.WM_NEWS_SINGLE_IMAGE:WemediaContans.WM_NEWS_MANY_IMAGE);
                createNewsMaterial(news,newList,WemediaContans.WM_COVER_REFERENCE);
            }
        }
        updateById(news);
    }
    //创建关联表数据
    private void createNewsMaterial(WmNews news,List<String> imgUrlList,short type){
        List<WmMaterial> wmMaterials = wmmaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imgUrlList));
        WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
        if (wmMaterials.size()>0){
            for (int i = 0; i < wmMaterials.size(); i++) {
                wmNewsMaterial.setMaterialId(wmMaterials.get(i).getId());
                wmNewsMaterial.setNewsId(news.getId());
                wmNewsMaterial.setType(type);
                wmNewsMaterial.setOrd((short)i);
                wmnewsMaterialMapper.insert(wmNewsMaterial);
            }
        }
    }
}
